import { GridActionsCellItem } from "@mui/x-data-grid";
import React from "react";
import { useEffect } from "react";
import { useContext } from "react";
import Dataform from "../../../components/Dataform";
import { TitleContext } from "../../../router";

import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import { useState } from "react";
import ConfirmDialog from "../../../components/ConfirmDialog";
import { Box, Button, Tooltip } from "@mui/material";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import { renderCellExpand } from "../../../components/RenderCellExpand";
import { useMutation } from "@tanstack/react-query";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import {
  GET_ALL_ACCOUNT,
  HANDLE_TEACHER_ACCOUNT,
  PASSWORD_RESET,
} from "../../../constants/url";
import { useSnackbar } from "notistack";

export default function TeacherAccount() {
  const nowTitle = useContext(TitleContext);
  useEffect(() => {
    nowTitle.setnowTitle(0);
  }, []);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [dialogData, setDialogData] = useState({});
  const [mx, setMx] = useState();
  const [rows, setRows] = useState([]);

  const handleDelete = (id) => {
    setConfirmOpen(false);
    //这里执行删除操作
    changeMutate({
      url: HANDLE_TEACHER_ACCOUNT,
      method: "delete",
      params: { id: id },
      useToken: true,
    });
    setRows(rows.filter((t) => t.id != id));
  };

  const handleDeleteClick = (e) => {
    setDialogData({
      text: "你确定要删除id为" + e + "的账号吗？",
      handleClose: () => setConfirmOpen(false),
      handleConfirm: () => handleDelete(e),
    });
    setConfirmOpen(true);
  };
  const handleReset = (id) => {
    setConfirmOpen(false);
    //在这里进行密码重置
    changeMutate({
      url: PASSWORD_RESET,
      method: "get",
      params: {
        user: rows.filter((val) => val.id == id)[0].userId,
      },
      useToken: true,
    });
  };
  const handleResetPwdClick = (e) => {
    setDialogData({
      text: "你确定要将此账号的密码重置为123456吗？",
      handleClose: () => setConfirmOpen(false),
      handleConfirm: () => handleReset(e),
    });
    setConfirmOpen(true);
  };
  const columns = [
    {
      field: "id",
      headerName: "序号",
      // flex: 1,
      width: 20,
      editable: false,
    },
    {
      field: "userId",
      headerName: "工号",
      width: 100,
      renderCell: renderCellExpand,
      editable: true,
    },
    {
      field: "name",
      headerName: "姓名",
      width: 100,
      renderCell: renderCellExpand,
      editable: true,
    },
    {
      field: "gender",
      headerName: "性别",
      width: 30,
      editable: true,
    },
    {
      field: "title",
      headerName: "职称",
      renderCell: renderCellExpand,
      flex: 1,
      editable: true,
    },
    {
      field: "college",
      renderCell: renderCellExpand,
      headerName: "学院",
      flex: 2,
      editable: true,
    },
    {
      field: "educationBackground",
      headerName: "教育背景",
      renderCell: renderCellExpand,
      flex: 5,
      editable: true,
    },
    {
      field: "degree",
      headerName: "学位",
      renderCell: renderCellExpand,
      flex: 3,
      editable: true,
    },
    {
      field: "actions",
      type: "actions",
      headerName: "操作",
      width: 100,
      cellClassName: "actions",
      getActions: ({ id }) => {
        return [
          <Tooltip title="删除账号">
            <GridActionsCellItem
              icon={<DeleteIcon />}
              label="Delete"
              onClick={() => handleDeleteClick(id)}
              color="inherit"
            />
          </Tooltip>,
          <Tooltip title="重置密码">
            <GridActionsCellItem
              icon={<RestartAltIcon />}
              label="重置密码"
              onClick={() => handleResetPwdClick(id)}
              color="inherit"
            />
          </Tooltip>,
        ];
      },
    },
  ];

  const {
    isLoading: getLoading,
    isSuccess: getSuccess,
    isError: getError,
    mutate: getMutate,
    data: getData,
  } = useMutation(["getAccountInfo"], mutateQueryFn);

  const {
    isLoading: changeLoading,
    isSuccess: changeSuccess,
    data: changeData,
    isError: changeError,
    mutate: changeMutate,
  } = useMutation(["changeAccount"], mutateQueryFn);
  useEffect(() => {
    if (getSuccess) {
      setRows(getData.data.data);
    }
  }, [getSuccess]);

  useEffect(() => {
    getMutate({
      url: GET_ALL_ACCOUNT,
      method: "get",
      params: { role: 1 },
      useToken: true,
    });
  }, []);
  const { enqueueSnackbar } = useSnackbar();
  useEffect(() => {
    if (changeSuccess) {
      if (changeData.data.code === -1) {
        enqueueSnackbar(changeData.data.data, { variant: "error" });
        return;
      }
      enqueueSnackbar("信息修改成功", { variant: "success" });

      findMax();
    }
  }, [changeSuccess]);

  const handleChange = async (newRow) => {
    //在这里发起请求
    // console.log(newR);
    changeMutate({
      url: HANDLE_TEACHER_ACCOUNT,
      method: newRow.id > mx ? "put" : "post",
      params: newRow.id > mx ? { password: "123456" } : { id: newRow.id },

      data: {
        userId: newRow.userId ?? "待完善",
        gender: newRow.gender ?? "待完善",
        title: newRow.title ?? "待完善",
        college: newRow.college ?? "待完善",
        educationBackground: newRow.educationBackground ?? "待完善",
        degree: newRow.degree ?? "待完善",
        name: newRow.name ?? "待完善",
      },
      useToken: true,
    });
    return newRow;
  };

  const findMax = () => {
    var mx = 0;
    for (var i in rows) {
      if (rows[i].id > mx) mx = rows[i].id;
    }
    setMx(mx);
    return mx + 1;
  };
  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
      }}
    >
      <Dataform
        fileName="教师信息"
        loading={getLoading || changeLoading}
        processRowUpdate={handleChange}
        rows={rows}
        columns={columns}
      />
      <Button
        variant="contained"
        onClick={() => {
          setRows([
            ...rows,
            {
              id: findMax(),
              userId: "待完善",
              name: "待完善",
              gender: "待完善",
              title: "待完善",
              college: "待完善",
              educationBackground: "待完善",
              degree: "待完善",
            },
          ]);
        }}
        sx={{ marginTop: 4 }}
      >
        添加新账号
      </Button>
      <ConfirmDialog {...dialogData} open={confirmOpen} />
    </Box>
  );
}
